using MauiTurntable.ViewModel;

namespace MauiTurntable;

public partial class cvTurnTable : ContentView
{
    cvTurnTableModel mode { get; set; }
    public cvTurnTable()
    {
        InitializeComponent();
        mode = this.BindingContext as cvTurnTableModel;
        mode.Re += Mpde_Re;
        mode.Rotation += Mpde_Rotation;
        this.Loaded += CvTurnTable_Loaded;
        this.SizeChanged += CvTurnTable_SizeChanged;
    }

    private void CvTurnTable_SizeChanged(object? sender, EventArgs e)
    {
        Mpde_Re();
    }

    private void CvTurnTable_Loaded(object? sender, EventArgs e)
    {
        Mpde_Re();
    }

    private void Mpde_Rotation(int obj)
    {
        MainThread.BeginInvokeOnMainThread(new Action(async () =>
        {
            view.Rotation = 0;
            var dst = await view.RotateTo(obj, 3000);
            if (!dst)
            {
                obj += 3 * 90;
                while (obj > 360)
                {
                    obj -= 360;
                }
                //  var dstshowValue = mode.SelectGroup + ":"+ obj+":";
                var dstshowValue = mode.SelectGroup + ":";
                var gitem = mode.Graphics.graphicsDrawableItems.Find(x => obj > x.startAngle && obj <= x.endAngle);
                if (gitem != null)
                {
                    dstshowValue += gitem.drawText;
                }
                mode.CheckItem = dstshowValue;
            }
        }));
    }

    private void Mpde_Re()
    {
        MainThread.BeginInvokeOnMainThread(new Action(() =>
        {
            view.Rotation = 0;
            Grid views = view.Parent as Grid;
            //btn.Text = $"ת:{views.Width.ToString("F0")} {views.Height.ToString("F0")}";
            if (view.Height <= 0 || view.Width <= 0)
            {
                return;
            }
            mode.Graphics.dirtyRect.Width = (float)views.Width;
            mode.Graphics.dirtyRect.Height = (float)views.Height;
            view.Invalidate();
        }));


    }
}